<template>
	<view class="penrecord_wrap page template-page">
		<view class="content">
			<view class="form-wrapper flex_1 left-page">
				<u-form :model="formData" ref="uForm" :border-bottom="false" :label-width="200" label-align="right">
					<u-form-item label="询问次数：" prop="time" :border-bottom="false">
						<u-number-box class="number-box" v-model="formData.time" bg-color="#fff" :min="1" :step="1"></u-number-box>
					</u-form-item>
					<u-form-item label="开始时间：" prop="startTime" :border-bottom="false">
						<FormItemDateTime v-model="formData.startTime" placeholder="请选择 开始时间" @showAfter="showDateTimeAfter('startTime')" />
					</u-form-item>
					<u-form-item label="结束时间：" prop="endTime" :border-bottom="false">
						<FormItemDateTime v-model="formData.endTime" placeholder="请选择 结束时间" @showAfter="showDateTimeAfter('endTime')" />
					</u-form-item>
					<u-form-item label="案发地点：" prop="address" :border-bottom="false">
						<FormItemText v-if="!isNetworkConnected" v-model="formmatAddressVal" />
						<FormItemMap v-else v-model="formmatAddressVal" />
					</u-form-item>
					<view class="form-group">
						<view class="form-group_header">
							<text class="iconfont form-group_icon">&#xe671;</text>
							<text class="form-group_text">询问人</text>
						</view>
						<u-form-item label="询问人：" prop="inquirytorName" :border-bottom="false">
							<FormItemText v-if="!isNetworkConnected" v-model="formData.inquirytor" />
							<FormItemLargeSelect v-else v-model="formData.inquirytorName" multiple filterable allowCreate :list="userList" labelText="nickName" valueText="userId" descText="dept.deptName" @change="onSelectChange($event, 'inquirytor')" />
						</u-form-item>
					</view>
					<view class="form-group">
						<view class="form-group_header">
							<text class="iconfont form-group_icon">&#xe671;</text>
							<text class="form-group_text">记录人</text>
						</view>
						<u-form-item label="记录人：" prop="recordtorName" :border-bottom="false">
							<FormItemText v-if="!isNetworkConnected" v-model="formData.recordtor" />
							<FormItemLargeSelect v-else v-model="formData.recordtorName" :list="userList" labelText="nickName" valueText="userId" @change="onSelectChange($event, 'recordtor')" />
						</u-form-item>
					</view>
					<view class="form-group">
						<view class="form-group_header">
							<text class="iconfont form-group_icon">&#xe671;</text>
							<text class="form-group_text">被询问人</text>
							<button v-if="isNetworkConnected" type="success" size="mini" style="margin: 0;" @click="uploadIdCardImg">身份证识别</button>
						</view>
						<view class="row">
							<u-form-item label="被询问人：" prop="reInquirytorName" :border-bottom="false">
								<FormItemText v-model="formData.reInquirytorName" />
							</u-form-item>
							<u-form-item label="性别：" prop="reInquirytorSex" :border-bottom="false">
								<FormItemSelect v-model="formData.reInquirytorSex" :list="INQUIRYSEX_LIST" />
							</u-form-item>
						</view>
						<view class="row">
							<u-form-item label="年龄：" prop="reInquirytorAge" :border-bottom="false">
								<FormItemText v-model="formData.reInquirytorAge" type="number" />
							</u-form-item>
							<u-form-item label="人大代表：" prop="reInquirytorIsNpc" :border-bottom="false">
								<FormItemSelect v-model="formData.reInquirytorIsNpc" :list="INQUIRYNPC_LIST" />
							</u-form-item>
						</view>
						<u-form-item label="出生日期：" prop="reInquirytorBirth" :border-bottom="false">
							<FormItemDateTime v-model="formData.reInquirytorBirth" format="yyyy年mm月dd日" valueFormat="yyyy-mm-dd" :dateParams="{
                                    year: true,
                                    month: true,
                                    day: true,
                                }" placeholder="请选择 出生日期" @showAfter="showDateTimeAfter('reInquirytorBirth')" />
						</u-form-item>
						<u-form-item label="证件类型：" prop="reInquirytorCardType" :border-bottom="false">
							<FormItemSelect v-model="formData.reInquirytorCardType" :list="INQUIRYCARD_LIST" />
						</u-form-item>
						<u-form-item label="证件号码：" prop="reInquirytorCardNum" :border-bottom="false">
							<FormItemText v-model="formData.reInquirytorCardNum"  />
						</u-form-item>
						<u-form-item label="联系电话：" prop="reInquirytorPhone" :border-bottom="false">
							<FormItemText v-model="formData.reInquirytorPhone" type="number" />
						</u-form-item>
						<u-form-item label="现住址：" prop="reInquirytorAddressNow" :border-bottom="false">
							<FormItemText v-model="formData.reInquirytorAddressNow" />
						</u-form-item>
						<u-form-item label="户籍：" prop="reInquirytorAddressOld" :border-bottom="false">
							<FormItemText v-model="formData.reInquirytorAddressOld" />
						</u-form-item>
						<u-form-item label="到达时间：" prop="reInquirytorStartTime" :border-bottom="false">
							<FormItemDateTime v-model="formData.reInquirytorStartTime" placeholder="请选择 到达时间" @showAfter="showDateTimeAfter('reInquirytorStartTime')" />
						</u-form-item>
						<u-form-item label="离开时间：" prop="reInquirytorEndTime" :border-bottom="false">
							<FormItemDateTime v-model="formData.reInquirytorEndTime" placeholder="请选择 离开时间" @showAfter="showDateTimeAfter('reInquirytorEndTime')" />
						</u-form-item>
						<view class="row">
							<u-form-item label="到达方式：" prop="reInquirytorGoType" :border-bottom="false">
								<FormItemSelect v-model="formData.reInquirytorGoType" :list="INQUIRYGO_LIST" />
							</u-form-item>
							<u-form-item label="本人签名：" prop="reInquirytorSignature" :border-bottom="false">
								<image class="sign-img" v-show="formData.reInquirytorSignature" :src="formData.reInquirytorSignature" />
								<text style="color: #1e9fff;width: 60rpx;" @click="startSign">签名</text>
							</u-form-item>
						</view>
						<u-form-item label="录音：" prop="imgUrl" :border-bottom="false">
							<FileChoose :value="formDataImgUrlList" :config="fileChooseConfig" @on-upload="handleOnUpload" @on-remove="handleOnRemove">
							</FileChoose>
						</u-form-item>
						<u-form-item label="" prop="reInquirytorName" :border-bottom="false">
							<view style="display: flex;">
								<u-button @click="toApp('com.kimcy929.secretvideorecorder')">全程录频</u-button>
								<u-button @click="toApp('com.huawei.soundrecorder')">全程录音</u-button>
							</view>
						</u-form-item>
						<u-form-item label="询问对象：" prop="archivesQuestionsPerson" :border-bottom="false">
							<uni-data-select v-model="formData.archivesQuestionsPerson" :localdata="inquiryTargetList" @change="archivesQuestionsPersonRangeChange" placeholder="请选择询问对象"></uni-data-select>
						</u-form-item>
						<u-form-item label="笔录内容：" prop="content" :border-bottom="false">
							<piaoyiEditor class='Editor' ref='piaoyiEditor' :values="formData.content" @changes="piaoyiEditoSaveContens" :maxlength="9999999" />
							<!-- <textarea  :value="formData.content" @input="piao"></textarea> -->
						</u-form-item>
					</view>
				</u-form>
			</view>
			<!-- 右侧模板预览 -->
			<PenrecordTem class="flex_1 template" ref='PenrecordTemRef' :formData="formData" :pdfDownload="pdfDownload" />
		</view>
		<DownloadBtn v-if="isNetworkConnected" class="download-btn" :pdfDownload="pdfDownload" title="询问笔录" :keyId="params.keyId" :formData="formData" :moduleName="currentModule.moduleName" @saveData="submitFormBackBefore" />
		<FooterBtn class="footer-btn" :pdfDownload="pdfDownload" @submit="submitForm" @cancel="handleCancel" />

		<EvidenceChainTabPopup v-model="questionBtnShow" :form="formData" :list="specificInquiryResponseList" @assignmentQuestion="assignmentQuestion" @assignmentAnswer="assignmentAnswer" />
	</view>
</template>

<script>
	import config from '@/common/config'
	import eventBus from '@/common/eventBus.js'
	import DataFlow from '@/pagesH5/mixins/DataFlow.js'

	import {
		INQUIRYGO_TYPE,
		INQUIRYSEX_LIST,
		INQUIRYCARD_LIST,
		INQUIRYGO_LIST,
		INQUIRYNPC_LIST
	} from '@/const/archives/penrecord.js'
	import {
		findStrIndex,
		checkType
	} from '@/utils/index';
	import {
		uploadLocalFile
	} from '@/static/common/js/padLocalFileHandler.js'

	import FormItemDateTime from '@/pagesH5/components/Form/formItemDateTime.vue'
	import FormItemMap from '@/pagesH5/components/Form/formItemMap.vue'
	import FormItemLargeSelect from '@/pagesH5/components/Form/formItemLargeSelect.vue'
	import FormItemSelect from '@/pagesH5/components/Form/formItemSelect.vue'
	import FormItemText from '@/pagesH5/components/Form/formItemText.vue'
	import FileChoose from '@/uni_modules/file-choose/components/file-choose/file-choose.vue'
	import piaoyiEditor from '@/uni_modules/piaoyi-editor/piaoyi-editor.vue'
	import PenrecordTem from '@/pagesH5/components/inquiryTemplate/penrecordTem.vue'
	import DownloadBtn from '@/pagesH5/components/DownloadBtn'
	import FooterBtn from '@/pagesH5/components/FooterBtn'
	import EvidenceChainTabPopup from './components/evidenceChainTabPopup.vue'

	export default {
		mixins: [DataFlow],
		components: {
			FormItemDateTime,
			FormItemMap,
			FormItemLargeSelect,
			FormItemSelect,
			FormItemText,
			FileChoose,
			piaoyiEditor,
			PenrecordTem,
			DownloadBtn,
			FooterBtn,
			EvidenceChainTabPopup
		},
		data() {
			return {
				INQUIRYSEX_LIST,
				INQUIRYCARD_LIST,
				INQUIRYGO_LIST,
				INQUIRYNPC_LIST,
				focusedField: null,
				userList: [],
				fileChooseConfig: {
					size: 20,
					limit: 99,
					title: "",
					headers: this.headers,
					formData: {},
					automatic: false,
					fileMediatype: 'file',
					mediaTypeFileType: 'mp3,wav,m4a,amr,flac'
				},
				imgUrlList: [],
				inquiryTargetList: [],
				questionBtnShow: false,
				specificInquiryResponseList: [],
				questionList: [],
				allTemplateList: [],
				isPutAway: false,
			}
		},
		computed: {
			formmatAddressVal: {
				get() {
					if (!this.formData.address) return this.formData.address
					if (!this.isNetworkConnected && checkType(this.formData.address) === 'string') return this.formData
						.address.split(',')[2]
					if (checkType(this.formData.address) === 'string') {
						return this.formData.address
					} else if (checkType(this.formData.address) === 'array') {
						return this.formData.address.join(',')
					}
				},
				set(val) {
					if (!this.isNetworkConnected) {
						this.formData.address = ',,' + val
					} else {
						this.formData.address = val
					}
				}
			},
			formDataImgUrlList: {
				get() {
					return this.imgUrlList
				}
			},
			cardUploadUrl() {
				return config.baseUrl + config.adminPath + '/archives/notice/discern';
			},
			basicData() {
				return this.vuex_basicData
			}
		},
		created() {


		},
		mounted() {
			// #ifdef APP-PLUS || APP

			let {
				dictData: {
					inquiryTargets
				},
				templeteList
			} = this.basicData
			if (inquiryTargets) {
				this.inquiryTargetList = inquiryTargets.map(item => {
					return {
						text: item.label,
						value: item.value
					};
				})
				this.allTemplateList = templeteList
			}
			// #endif
			if (this.isNetworkConnected) {
				this.$u.api.systemUser
					.list({
						status: 0,
						pageNum: 1,
						pageSize: 999
					})
					.then(res => {
						if (res.code == 200) {
							let list = res.rows.map(person => {
								return {
									...person,
									isSelect: false
								};
							});
							this.userList = list
						}
					});
			}
		},
		onShow() {
			eventBus.$on('get-sign-event', base64 => {
				this.$set(this.formData, 'reInquirytorSignature', base64)
			})
		},
		methods: {
			showDateTimeAfter(field) {
				this.focusedField = field
			},
			onSelectChange(params, key) {
				const {
					list,
					value,
					item
				} = params
				const keyOrg = key + 'Org'
				let orName = item.map(item => item.nickName).join(' ');
				let orOrg = item.map(item => item.dept.deptName).join(' ');
				if (value) {
					const arr1 = value.split(',');
					const arr2 = item.map(item => item.userId);
					const diff = arr1.filter(id => {
						return !arr2.some(id2 => id2 == id)
					});
					diff.forEach(id => {
						const [org, name] = id.split('-');
						if (org && name) {
							orOrg += ` ${org}`;
							orName += ` ${name}`;
						} else {
							// 如果没有写分隔符，那么默认第一个分割的是 名字
						}
					})
					const orOrgArr = [...new Set(orOrg.split(' '))];
					const orOrgResult = orOrgArr.join(' ');
					Object.assign(this.formData, {
						[keyOrg]: orOrgResult,
						[key]: orName
					});
				} else {
					Object.assign(this.formData, {
						[keyOrg]: '',
						[key]: ''
					});
				}
			},
			uploadIdCardImg() {
				let _this = this
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function(res) {
						const tempFilePaths = res.tempFilePaths[0];
						// 图片上传
						const uploadTask = uni.uploadFile({
							url: _this.cardUploadUrl,
							filePath: tempFilePaths,
							name: 'file',
							header: _this.headers,
							success: function(res) {
								_this.handleOnSuccess(JSON.parse(res.data))
							},
							fail: function(uploadFileFail) {},
							complete: () => {}
						});
					},
					error: function(e) {}
				});
			},
			handleOnSuccess(res) {
				if (!res.data.words_result_num) {
					uni.showToast({
						title: '无法识别，请上传清晰的证件照片',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: '识别成功',
						icon: 'none'
					});
					const {
						姓名: {
							words: reInquirytorName
						},
						性别: {
							words: reInquirytorSex
						},
						出生: {
							words: reInquirytorBirth
						},
						公民身份号码: {
							words: reInquirytorCardNum
						},
						住址: {
							words: reInquirytorAddressOld
						}
					} = res.data.words_result;
					let day = ''
					if (reInquirytorBirth) day = new Date(
						`${reInquirytorBirth.slice(0, 4)},${parseInt(reInquirytorBirth.slice(4, 6))},${reInquirytorBirth.slice(6, 8)}`
					);
					Object.assign(this.formData, {
						reInquirytorName,
						reInquirytorSex: reInquirytorSex === '男' ? 0 : reInquirytorSex === '女' ? 1 : '',
						reInquirytorBirth: this.$u.timeFormat(day, "{y}-{m}-{d}"),
						reInquirytorCardNum,
						reInquirytorCardType: res.data?.idcard_number_type === 1 ? '0' : res?.data
							.idcard_number_type === 0 ? '1' : '',
						reInquirytorAddressOld,
						reInquirytorAge: day ? new Date().getFullYear() - day.getFullYear() : ''
					});
					this.$forceUpdate()
				}
				this.loadding = false;
			},
			handleOnUpload(file) {
				this.imgUrlList.push(file)
			},
			handleOnRemove(fileList, index) {
				let newFileList = fileList
				this.imgUrlList = [...newFileList]
			},
			toApp(name) {
				plus.runtime.launchApplication({
						pname: name
					},
					function(e) {}
				);
			},
			archivesQuestionsPersonRangeChange(type) {
				this.specificInquiryResponseList = this.allTemplateList.filter(tem => {
					return tem.type == 0 && tem.personType == type
				})
				this.questionBtnShow = true
			},
			async startSign() {
				uni.navigateTo({
					url: '/pagesH5/components/signComponent'
				})
			},
			putAwayRight() {
				this.isPutAway = !this.isPutAway;
			},
			piaoyiEditoSaveContens(e) {
				this.$set(this.formData, 'contentRender', e.html)
				this.$set(this.formData, 'content', e.delta)
			},
			assignmentQuestion(item) {
				let temItem = this.questionList.find(tem => tem.questionId == item.questionId && tem.temId == item.temId)
				if (temItem) {
					const arr = this.questionList;
					arr.forEach((tem, index) => {
						if (tem.questionId == item.questionId) {
							const start = findStrIndex(this.formData.content, '问：', index);
							const end = findStrIndex(this.formData.content, '问：', index + 1);
							const startIndex = start > 0 ? start : 0;
							const endIndex = end > 0 ? end : this.formData.content.length;
							this.formData.content.substring(start, end);
							let str = this.formData.content.replace(this.formData.content.substring(startIndex !=
								0 ? startIndex - 1 : startIndex, endIndex), '');
							this.questionList.splice(index, 1);
							this.$set(this.formData, 'content', str)
							this.$refs.piaoyiEditor.update(str)
							setTimeout(() => {
								this.$refs.piaoyiEditor.saveContens()
							})
						}
					});
				} else {
					this.questionList.push({
						questionId: item.questionId,
						temId: item.temId
					});
					let str = (this.formData.content || '') + `${!this.formData.content ? '' : '\n'}` + '问：' + item
						.question.trim() + '\n答：';
					this.$set(this.formData, 'content', str)
					this.$refs.piaoyiEditor.update(str)
					// setTimeout(() => {
					// 	this.$refs.piaoyiEditor.saveContens()
					// })
				}
			},
			assignmentAnswer(item) {
				console.log(item);
				let str = (this.formData.content || '') + item.answer;
				this.$set(this.formData, 'content', str)
				this.$refs.piaoyiEditor.update(str)
				setTimeout(() => {
					this.$refs.piaoyiEditor.saveContens()
				})
			},
			initForm() {
				const {
					doOrg,
					fireAddress,
					doPerson,
					doPersonName,
					doOtherPerson,
					doOtherPersonName
				} = this.archivesData
				console.log(this.archivesData);
				const currentTime = this.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss');
				const inquiryStr = `${doPerson || ''}${doOtherPerson ? `,${doOtherPerson}` : ''}`
				const inquiryArr = inquiryStr.split(',')
				const uniqueInquiry = [...new Set(inquiryArr)]

				const inquiryNameStr = `${doPersonName || ''}${doOtherPersonName ? `,${doOtherPersonName}` : ''}`
				const inquiryNameArr = inquiryNameStr.split(',')
				const uniqueInquiryName = [...new Set(inquiryNameArr)]

				let initForm = {
					remark: '',
					time: 1,
					startTime: currentTime,
					endTime: currentTime,
					address: fireAddress || '',
					inquirytorName: uniqueInquiry.join(','),
					inquirytor: uniqueInquiryName.join(','),
					inquirytorOrg: doOrg || '',
					recordtorName: doPerson,
					recordtor: doPersonName || '',
					recordtorOrg: doOrg || '',
					reInquirytorName: '',
					reInquirytorSex: '',
					reInquirytorAge: '',
					reInquirytorBirth: '',
					reInquirytorCardType: '',
					reInquirytorCardNum: '',
					reInquirytorIsNpc: '',
					reInquirytorPhone: '',
					reInquirytorAddressNow: '',
					reInquirytorAddressOld: '',
					reInquirytorGoType: INQUIRYGO_TYPE.VERBALSUMMONS,
					reInquirytorStartTime: currentTime,
					reInquirytorEndTime: currentTime,
					reInquirytorSignature: '',
					imgUrl: '',
					content: '',
					questionBtnShow: false,
					archivesQuestionsList: '',
					activeCollapse: ''
				};
				return initForm
			},
			afterHandleData(data) {
				if (this.$refs.piaoyiEditor && data.content) {
					this.$refs.piaoyiEditor.update(data.content)
				}
				this.imgUrlList = data.imgUrl ?
					data.imgUrl.split(',').map(s_item => ({
						type: s_item.substring(s_item.lastIndexOf('.') + 1),
						name: s_item.substring(s_item.lastIndexOf("/") + 1),
						url: s_item
					})) : [];
			},
			async submitFormBefore() {
				this.formData.title =
					`${this.formData.reInquirytorName || ''}${this.$u.timeFormat(new Date(), 'yyyymmddhhMM')}`
				const uploadTasks = [];
				for (const file of this.imgUrlList) {
					uploadTasks.push(uploadLocalFile(this.params.archivesId, file));
				}
				const results = await Promise.all(uploadTasks);
				let list = this.imgUrlList.map((url, index) => {
					return results[index]
				})
				this.formData.imgUrl = list.join(',')
			}
		}
	}
</script>
<style scoped lang="scss">
	.penrecord_wrap {

		&>.content {
			.form-wrapper {
				background: #fff;
				padding-left: 20rpx;
				padding-right: 20rpx;

				.form-group {
					&_header {
						width: 100%;
						display: flex;
						align-items: center;
						height: 50px;
						line-height: 50px;
						border-bottom: 2rpx solid #eee;
						margin-bottom: 20rpx;
					}

					&_icon {
						margin-right: 8px;
						font-size: 20px;
						color: #000000d9
					}

					&_text {
						font-size: 16px;
						font-weight: bold;
						color: #000000d9
					}

					.row {
						display: flex;

						.u-form-item {
							flex: 1;
						}
					}
				}
			}
		}



		.Editor {
			box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px;
			width: 100%;
			max-width: 100%;
			overflow: hidden;
		}
	}

	::v-deep .form-wrapper {
		.u-form-item {
			padding: 0 10rpx;
			line-height: 1;

			.u-form-item__body {
				margin-bottom: 36rpx;
				min-height: 68rpx;
				line-height: 1;

				.u-form-item--right__content {
					height: 100%;

					.u-form-item--right__content__slot {
						height: 100%;

						.form-item_value {
							height: 100%;
							flex: 1;
							display: flex;
							align-items: center;
						}

						.form-item_icon {
							height: 100%;
							width: 50rpx;
							text-align: center;
							color: #c0c4cc;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
				}
			}
		}

		.number-box {
			width: 100%;
			height: 100%;
			border: 2rpx solid #dcdfe6;
			color: #606266;
			background: #fff;
			border-radius: 8rpx;

			.u-icon-plus,
			.u-icon-minus,
			.u-number-input {
				background-color: #f5f7fa;
			}

			.u-number-input {
				margin: 0;
				flex: 1;
			}

			.u-icon-minus {
				border-radius: 8rpx 0 0 8rpx;
				border-right: 2rpx solid #dcdfe6;
			}

			.u-icon-plus {
				border-radius: 0 8rpx 8rpx 0;
				border-left: 2rpx solid #dcdfe6;
			}
		}
	}
</style>